<template>
  <a-page-header>
    <a-card>
      <div class="table-page-search-wrapper">
        <a-form-model layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-model-item label="查询用户">
                <a-input v-model="userLike"  placeholder="查询用户"/>
              </a-form-model-item>
            </a-col>

            <a-col :md="4" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="queryLike">查询</a-button>
                <a-button style="margin-left: 8px">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form-model>
      </div>

      <a-table :columns="columns" :data-source="data"
               :loading="loading" :rowKey="record => record.userId"
               @change="handleTableChange">

        <template #title>
          <a-button type="primary" icon="plus-circle" style="margin-left: 10px;" @click="showAddModal">
            新增用户
          </a-button>
          <a-modal
              :title="modal.title"
              :visible="modal.visible"
              :confirm-loading="modal.confirmLoading"
              okText="提交" cancelText="取消"
              @ok="handleModalOk" @cancel="handleModalCancel">

            <a-form-model :model="form" ref="form" @submit="handleModalFormSubmit"
                          :label-col="{span:5}" :wrapper-col="{span:14}" :rules="modal.rules">
              <a-form-model-item label="用户名" ref="username" prop="username">
                <a-input v-model="form.username" placeholder="用户名"  />
              </a-form-model-item>

              <a-form-model-item v-if="!modal.isDisabled" label="密码" ref="password" prop="password">
                <a-input-password v-model="form.password"
                                  :placeholder="modal.passwordSwitch?'随机生成密码':'请输入密码'"
                                  :disabled="modal.passwordSwitch"  />

              </a-form-model-item>
              <a-form-model-item label="用户昵称" ref="nickname" prop="nickname">
                <a-input v-model="form.nickname" placeholder="请输入用户昵称"  />
              </a-form-model-item>
              <a-form-model-item label="邮箱" ref="email" prop="email">
                <a-input v-model="form.email" placeholder="请输入邮箱"  />
              </a-form-model-item>

              <a-form-model-item label="电话" ref="phone" prop="phone">
                <a-input v-model="form.phone" placeholder="请输入电话"  />
              </a-form-model-item>

              <a-form-model-item label="性别" ref="gender" prop="gender">
                <a-radio-group v-model="form.gender" button-style="solid">
                  <a-radio-button value="1">
                    男
                  </a-radio-button>
                  <a-radio-button value="0">
                    女
                  </a-radio-button>
                  <a-radio-button value="2">
                    保密
                  </a-radio-button>
                </a-radio-group>
              </a-form-model-item>


              <a-form-model-item label="是否启用" ref="status" prop="status">
                <a-radio-group v-model="form.status" button-style="solid">
                  <a-radio-button value="1">
                    启用
                  </a-radio-button>
                  <a-radio-button value="0">
                    禁用
                  </a-radio-button>
                </a-radio-group>
              </a-form-model-item>

              <a-form-model-item v-if="!modal.isDisabled" label="密码生成方式">
                <a-switch checked-children="随机" un-checked-children="自定义" v-model="modal.passwordSwitch"
                          @change="passwordSwitchChange" />
              </a-form-model-item>

            </a-form-model>
          </a-modal>
        </template>

        <a slot="username" slot-scope="username" >{{ username }}</a>
        <span slot="gender" slot-scope="gender">

      <a-tag v-if="gender==='1'" :color="'purple'">
        <span >Male</span>
      </a-tag>
      <a-tag v-else-if="gender==='0'" :color="'orange'">
        <span >Female</span>
      </a-tag>
      <a-tag v-else :color="'red'">
        <span>Unknown</span>
      </a-tag>
    </span>
        <span slot="status" slot-scope="status">
       <a-tag :color="status?'green':'volcano'">
        <span v-if="status">启用</span>
         <span v-else>禁用</span>
      </a-tag>
    </span>

        <template #action="record">
          <a-button type="primary" shape="circle" icon="edit" @click="showEditModal(record)" />
          <a-divider type="vertical" />
          <a-popconfirm
              :title="`确认要删除:${record.username}吗?`"
              ok-text="确认"
              cancel-text="取消"
              @confirm="handleDeleteUser(record.userId)"
          >
            <a-icon slot="icon" type="question-circle-o" style="color: red" />
            <a-button type="danger" shape="circle" icon="delete" />
          </a-popconfirm>
          <a-divider type="vertical" />
          <a-button type="primary" ghost @click="showUserPerm(record)">分配角色</a-button>
        </template>
      </a-table>
      <a-modal
          key="userAuth"
          :width="740"
          :title="transfer.title"
          :visible="transfer.visible"
          :confirm-loading="transfer.confirmLoading"
          okText="保存用户角色" cancelText="取消"
          @ok="handleTransferOk" @cancel="handleTransferCancel">
        <a-transfer
            :key="'userTransfer'+new Date().getTime()"
            :data-source="transfer.roles"
            :titles="['备选角色', '已选角色']"
            :list-style="{
              width: '300px',
              height: '300px',
            }"
            :selected-keys="transfer.selectedKeys"
            :target-keys="transfer.targetKeys"
            :render="item => item.title"
            @change="handleChange"
            @selectChange="handleSelectChange"
            @scroll="handleScroll"
        />
      </a-modal>
    </a-card>

  </a-page-header>
</template>

<script>

import {
  getAllUserList,
  addUser,
  updateUser,
  deleteUser,
  checkedRoles,
  addOrDeleteUserRole,
  queryUserLike
} from "@/api/user";

const columns = [
  {
    dataIndex: 'userId',
    key:'userId',
    title: '用户标识'
  },
  {
    dataIndex: 'username',
    key:'username',
    title: '用户名',
    scopedSlots: { customRender: 'username' },
  },
  {
    dataIndex: 'nickname',
    key:'nickname',
    title: '用户昵称'
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key:'email'
  },
  {
    title: '电话',
    key:'phone',
    dataIndex: 'phone'
  },
  {
    title: '性别',
    dataIndex: 'gender',
    scopedSlots: { customRender: 'gender' },
  },
  {
    title: '用户状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' },
  },
  {
    title: '创建时间',
    key:'createTime',
    dataIndex: 'createTime'
  },
  {
    title: '修改时间',
    key:'updateTime',
    dataIndex: 'updateTime'
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
  },
];
const rules = {
  username: [
    {required: true,pattern:'^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){4,19}$',
      message: '用户名为5-20个以字母开头、可带数字', trigger: ['blur','change']},
  ],
  nickname:[
    {required: true, message: '请输入昵称', trigger: ['blur']}
  ],
  email:[
    {required: true, message: '请输入正确的邮箱', trigger: ['blur','change'],type:'email'}
  ],
  phone: [
    {required: true, message: '请输入正确的手机号',pattern:'^1[0-9]{10}$', trigger: ['blur','change']},
  ],
  status:[
    {required: true, message: '请选择是否启用', trigger: 'blur'}
  ]
}
export default {
  name: "SystemUser",
  data(){
    return{
      userLike:'',
      columns,
      pagination: {},
      loading:false,
      data:[],
      modal:{
        title:'',
        visible:false,
        confirmLoading: false,
        isDisabled:false,
        passwordSwitch:true,
        rules
      },
      form:{
        headPic:'',
        userId:undefined,
        username:'',
        password:'',
        nickname:'',
        email:'',
        phone:'',
        gender:undefined,
        status:undefined
      },
      transfer:{
        title:'',
        currentUser:undefined,
        visible:false,
        confirmLoading: false,
        targetKeys:[],
        selectedKeys: [],
        roles:[],
      }
    }
  },
  mounted() {
    this.fetch()
  },
  methods:{
    queryLike(){
      queryUserLike(this.userLike).then(res=>{
        this.data = res.data
      })
    },
    handleTableChange(pagination, filters, sorter){
      console.log(pagination,filters,sorter)
    },
    showUserPerm(record){
      this.transfer.currentUser = record
      this.transfer.title = record.username+'用户角色分配'
      let _this = this
      checkedRoles(record.userId).then(res=>{
        let datsSource = res.data.roles.map(item =>{
          return {
            key:item.roleId.toString(),
            title:item.roleName,
            description:item.roleInfo
          }
        })
        _this.transfer.roles = datsSource
        const checkedRoleIds = res.data.checkedRoleIds.map(item => item.toString())

        _this.transfer.targetKeys = checkedRoleIds
        _this.transfer.visible = true
      })

    },
    handleTransferOk(){
      this.transfer.confirmLoading = true
      addOrDeleteUserRole({id:this.transfer.currentUser.userId,checkedIds:this.transfer.targetKeys})
      .then(res=>this.hs(res))
      .finally(()=>{
        this.transfer.confirmLoading = false
      })
    },
    hs(res){
      this.transfer.confirmLoading = false
      this.$notification['success']({
        message: '成功',
        description: `${res.data}`,
        duration: 8
      })
      this.showUserPerm(this.transfer.currentUser)
    },
    handleTransferCancel(){
      this.transfer.visible = false;
    },
    handleChange(nextTargetKeys, direction, moveKeys) {
      this.transfer.targetKeys = nextTargetKeys;
      console.log('targetKeys: ', nextTargetKeys);
      console.log('direction: ', direction);
      console.log('moveKeys: ', moveKeys);
    },
    handleSelectChange(sourceSelectedKeys, targetSelectedKeys) {
      this.transfer.selectedKeys = [...sourceSelectedKeys, ...targetSelectedKeys];
      console.log('sourceSelectedKeys: ', sourceSelectedKeys);
      console.log('targetSelectedKeys: ', targetSelectedKeys);
    },
    handleScroll(direction, e) {
      console.log('direction:', direction);
      console.log('target:', e.target);
    },
    fetch(params = {}){
      console.log(params)
      this.loading = true
      getAllUserList().then(res=>{
        this.data = res.data
      }).catch(err=>{
        console.log("SystemUser:fetch"+err.message)
      }).finally(()=>{
        this.loading = false
      })
    },

    // add or update Start
    passwordSwitchChange(){
      this.form.password = ""
    },
    showAddModal(){
      this.modal.title = '新增用户'
      this.modal.visible = true
      this.modal.isDisabled = false;
    },
    showEditModal(record){
      this.modal.title = '修改用户'
      this.modal.visible = true
      this.modal.isDisabled = true;
      let {headPic, userId, username, nickname, email, phone, gender, status} = record
      this.form = {
        headPic, userId, username, nickname, email, phone, gender,
            status:status?"1":"0"
      }
    },
    handleModalOk(){
      this.handleModalFormSubmit()
    },
    handleModalCancel(){
      this.modal.visible = false
      this.resetForm('form')
    },
    resetForm(formName) {
      this.form = {
        headPic:'',
        userId:undefined,
        username:'',
        password:'',
        nickname:'',
        email:'',
        phone:'',
        gender:undefined,
        status:undefined
      }
      this.$refs[formName].resetFields();
    },
    handleModalFormSubmit(){
      this.$refs['form'].validate(valid=>{
        if (valid) {
          let submitData = this.form
          submitData.status = this.form.status === "1"
          this.modal.confirmLoading = true
          if (this.modal.isDisabled){
            this.handleUpdateUser(submitData)
          }else {
            this.handleAddUser(submitData)
          }
        } else {
          this.handleFiled(new Error('表单校验不通过'))
          return false;
        }

      })
    },
    handleUpdateUser(user){
      updateUser(user).then(res=>{
        this.handleSuccess(res)
      }).catch(err=>this.handleFiled(err))
    },
    handleAddUser(user){
      addUser(user).then(res=>{
        this.handleSuccess(res)
      }).catch(err=>this.handleFiled(err))
      this.resetForm('form')
    },
    handleDeleteUser(userId){
        deleteUser(userId).then(res=>{
          this.handleSuccess(res)
        }).catch(err=>this.handleFiled(err))
    },
    handleSuccess(res){
      this.modal.confirmLoading = false
      this.$notification['success']({
        message: '成功',
        description: `${res.data}`,
        duration: 8
      })
      this.fetch()
    },
    handleFiled(err){
      this.modal.confirmLoading = false
      console.log(err.message)
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).message || {}).message||err.message || '请求出现错误，请稍后再试',
        duration: 4
      })
    }
    // add or update End
  }
}
</script>

<style lang="less">
.table-page-search-wrapper {

  .ant-form-inline {
    .ant-form-item {
      display: flex;
      margin-bottom: 24px;
      margin-right: 0;

      .ant-form-item-control-wrapper {
        flex: 1 1;
        display: inline-block;
        vertical-align: middle;
      }

      > .ant-form-item-label {
        line-height: 32px;
        padding-right: 8px;
        width: auto;
      }
      .ant-form-item-control {
        height: 32px;
        line-height: 32px;
      }
    }
  }

  .table-page-search-submitButtons {
    display: block;
    margin-bottom: 24px;
    white-space: nowrap;
  }
}
</style>
